package com.woniu.uums.service.impl;

import com.woniu.common.utils.GetCurrentUserId;
import com.woniu.common.utils.ResponseData;
import com.woniu.uums.pojo.MenuRole;
import com.woniu.uums.pojo.ZyManage;
import com.woniu.uums.service.MenuRoleService;
import com.woniu.uums.service.ZyManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.uums.mapper.MenuMapper;
import com.woniu.uums.pojo.Menu;
import com.woniu.uums.service.MenuService;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {


    @Autowired
    private ZyManageService zyManageService;

    @Autowired
    private MenuRoleService menuRoleService;

    @Override
    public ResponseData<?> selMenu() throws Exception {
        String userId = GetCurrentUserId.getUserId();
        ZyManage manage = zyManageService.lambdaQuery()
                .eq(ZyManage::getId, userId)
                .one();
        String manageRoleId = manage.getManageRoleId();
        // 中间表
        List<MenuRole> menuRoleList = menuRoleService.lambdaQuery()
                .eq(MenuRole::getRoleId, manageRoleId)
                .list();
        ArrayList<String> menuId = new ArrayList<>();
        for (MenuRole menuRole : menuRoleList) {
            menuId.add(menuRole.getMenuId());
        }
        List<Menu> allMenu = lambdaQuery()
                .eq(Menu::getStatus, 1)
                .in(Menu::getId, menuId)
                .list();

//        List<Menu> allMenu = lambdaQuery()
//                .eq(Menu::getStatus, 1)
//                .list();

        List<Menu> parentMenus = new ArrayList<>();     // 所有的父菜单集合
        for (Menu menu : allMenu) {
            if (menu.getParentId() == -1) {
                Menu parentMenu = new Menu();
                parentMenu.setId(menu.getId());
                parentMenu.setName(menu.getName());
                parentMenu.setLink(menu.getLink());
                parentMenu.setParentId(menu.getParentId());
                parentMenu.setIcon(menu.getIcon());
                parentMenu.setStatus(menu.getStatus());
                parentMenu.setChildren(null);
                parentMenus.add(parentMenu);
            }
        }

        for (Menu parentMenu : parentMenus) {
            ArrayList<Menu> childrenMenus = new ArrayList<>();
            for (Menu menu : allMenu) {
                if (menu.getParentId().equals(parentMenu.getId()) && menu.getParentId() != -1) {
                    childrenMenus.add(menu);
                }
            }
            parentMenu.setChildren(childrenMenus);
        }

        return new ResponseData<>().success(parentMenus);
    }
}
